import pandas as pd
from utils import log_info, log_exception, log_debug
from services.importers.base_importer import BaseImporter


class ExcelImporter(BaseImporter):
    """Excel文件导入器"""

    def read_file(self, file_path, progress_var=None, progress_label=None, import_dialog=None):
        """读取Excel文件并解析为题目数据"""
        try:
            log_debug(f"开始处理Excel文件: {file_path}")
            # 读取Excel文件，第一行为标题行
            df = pd.read_excel(file_path, skiprows=0)
            questions = df.to_dict('records')
            total = len(questions)
            log_debug(f"成功读取Excel文件，共{total}道题目")

            # 处理空值并格式化数据
            formatted_questions = []
            for q in questions:
                # 检查必要字段
                required_fields = ['Q', 'A', 'B', 'C', 'D', 'T', 'F', 'type']
                if not all(key in q for key in required_fields):
                    continue

                # 处理空值
                for key in q:
                    if pd.isna(q[key]):
                        q[key] = ''

                # 格式化数据
                formatted_q = {
                    'J': q.get('J', ''),
                    'P': q.get('P', ''),
                    'I': q.get('I', ''),
                    'Q': q.get('Q', ''),
                    'T': q.get('T', ''),
                    'A': q.get('A', ''),
                    'B': q.get('B', ''),
                    'C': q.get('C', ''),
                    'D': q.get('D', ''),
                    'F': q.get('F', ''),
                    'LA': int(float(q.get('LA', 0) or 0)),
                    'LB': int(float(q.get('LB', 0) or 0)),
                    'LC': int(float(q.get('LC', 0) or 0)),
                    'type': int(q.get('type', 0))
                }
                formatted_questions.append(formatted_q)

            return formatted_questions
        except Exception as e:
            log_exception(f"处理Excel数据时发生异常: {str(e)}")
            return []


def process_excel_data(file_path, progress_var=None, progress_label=None, import_dialog=None):
    """处理Excel数据并导入数据库"""
    importer = ExcelImporter()
    return importer.process_data(file_path, progress_var, progress_label, import_dialog)
